#pragma once

#include <iostream>
#include <string>
#include <set>
#include <cstdio>
#include "Common.hpp"
#include "InetAddr.hpp"

class Command
{
public:
    Command()
    {
        // 1. 添加远程命令白名单
        _WhiteListCommand.insert("ls");
        _WhiteListCommand.insert("pwd");
        _WhiteListCommand.insert("ls -l");
        _WhiteListCommand.insert("touch haha.txt");
        _WhiteListCommand.insert("whoami");
    }

    bool IsSafeCommand(const std::string& cmd)
    {
        auto iter = _WhiteListCommand.find(cmd); // 迭代器查找
        return iter != _WhiteListCommand.end();
    }

    // 2. 执行命令
    std::string Execute(const std::string& cmd, InetAddr &addr)
    {
        // 检查是否在白名单
        if(!IsSafeCommand(cmd))
        {
            return std::string("坏人！");
        }

        std::string who = addr.StringAddr(); // 执行者

        FILE *fp = popen(cmd.c_str(), "r");
        if(nullptr == fp)
        {
            return std::string("你要执行的命令不存在！");
        }
        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line; // 读取命令 
        }
        pclose(fp);
        std::string result =  who + " execute done, resault is : \n" + res;
        LOG(LogLevel::DEBUG) << result;
        return result;
    }
    ~Command()
    {}
private:
std::set<std::string> _WhiteListCommand;
};